package com.shiyu.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.shiyu.common.core.constants.HttpConstants;
import com.shiyu.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
//    从那个服务的配置文件拿去,取决于bean对象交给了哪一个服务的spring对象进行管理
    @Value("${jwt.secret}")
    private String secret;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        获取token
        System.out.println("拦截器");
       String token=getToken(request);
        tokenService.extendToken(token,secret);
        return true;
    }

    public String getToken(HttpServletRequest request){
//        身份认证标识
        String token=request.getHeader(HttpConstants.AUTHENTICATION);
//        取代前缀
        if(StrUtil.isNotEmpty(token)&&token.startsWith(HttpConstants.PREFIX)){
            token=token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;

    }

}
